package cn.ys.groupbuy;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;

import java.util.ArrayList;
import java.util.List;

import cn.handmark.pulltorefresh.library.PullToRefreshBase;
import cn.ys.refresh.PullToRefreshScrollView;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link TuanFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link TuanFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TuanFragment extends Fragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    private ViewPager viewPager;
    private List<View> bannerLayout;
    private LinearLayout dots_layout;
    private ImageView[] dots;
    private ImageView current_point;
    private int currentIndex = 0;
    private float offset = -1;
    private ScrollView tuanScrollView;
    private ListView tuan_listview;
    private PullToRefreshScrollView refreshScrollView;
    public static boolean isVisible = false;
    private TableLayout table_first, table_sec;
    private LinearLayout base_layout;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment TuanFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static TuanFragment newInstance(String param1, String param2) {
        TuanFragment fragment = new TuanFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public TuanFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       /* if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }*/
        //viewPager=new ViewPager(getActivity());
        bannerLayout = new ArrayList<View>();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        System.out.println("555555555555555555");
        View baseView = inflater.inflate(R.layout.fragment_base, null);
        base_layout = (LinearLayout) baseView.findViewById(R.id.base_layout);

        View view = inflater.inflate(R.layout.fragment_tuan, container, false);
        viewPager = (ViewPager) view.findViewById(R.id.banner);
        tuan_listview = (ListView) view.findViewById(R.id.tuan_listview);
        tuan_listview.setAdapter(new MyAdapter(getActivity()));
        dots_layout = (LinearLayout) view.findViewById(R.id.dots_layout);
        current_point = (ImageView) view.findViewById(R.id.current_point);
        refreshScrollView = (PullToRefreshScrollView) view.findViewById(R.id.tuan_refresh);
        refreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                new GetDataTask().execute();
            }
        });
        tuanScrollView = refreshScrollView.getRefreshableView();
        View banner_first = inflater.inflate(R.layout.banner_first, container, false);
        View banner_sec = inflater.inflate(R.layout.banner_sec, container, false);
        table_first = (TableLayout) banner_first.findViewById(R.id.table_first);
        TableRow row1 = (TableRow) table_first.getChildAt(0);
        row1.getChildAt(0).setOnClickListener(this);
        bannerLayout.add(banner_first);
        bannerLayout.add(banner_sec);
        viewPager.setAdapter(new MyViewPagerAdapter());
        viewPager.setOnPageChangeListener(new MyOnPagerChangeListener());
        viewPager.setCurrentItem(0);
        initDots();
        tuanScrollView.requestFocus();
        tuanScrollView.setFocusable(true);
        tuanScrollView.setFocusableInTouchMode(true);
        isVisible = true;
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    /*public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }*/

    public void initDots() {
        dots = new ImageView[bannerLayout.size()];
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(20, 0, 0, 0);
        for (int i = 0; i < bannerLayout.size(); i++) {
            ImageView point = new ImageView(getActivity());
            point.setBackgroundResource(R.drawable.icon_page2_off);
            dots[i] = point;
            dots[i].setLayoutParams(lp);
            dots_layout.addView(dots[i]);
        }
        currentIndex = 0;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        /*try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }*/
    }

    @Override
    public void onResume() {
        super.onResume();
        System.out.println("444444444444444444444444");
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        System.out.println("22222222222222222222222");
        if (isVisibleToUser) {
            isVisible = true;
            System.out.println("33333333333333333333333333");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        System.out.println("666666666666666666666");
        // mListener = null;
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getActivity(), CateActivity.class);
        startActivity(intent);
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

    class MyViewPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return bannerLayout.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(bannerLayout.get(position % bannerLayout.size()), 0);
            return bannerLayout.get(position % bannerLayout.size());
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(bannerLayout.get(position % bannerLayout.size()));
            super.destroyItem(container, position, object);
        }
    }

    class MyOnPagerChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            /*Animation animation=null;
            System.out.println("the onPageScrolled method parameters position value is : "+position+" positionOffset value is : "+positionOffset+"  positionOffsetPixels value is : "+positionOffsetPixels);
            if(currentIndex==0){
                animation=new TranslateAnimation(0,32,0,0);
            }
            if(currentIndex==1){
                animation=new TranslateAnimation(32,0,0,0);
            }
            currentIndex=position;
            animation.setFillAfter(true);
            animation.setDuration(300);
            current_point.startAnimation(animation);*/
            // float x= current_point.getX();
            // System.out.println("the current_point.getScrollX() = "+x);
            // System.out.println("the currentIndex value is : "+position+"  positionOffset value is : "+positionOffset);
            /*if(position==0){
                int x= (int) (positionOffset*32);
                current_point.scrollBy(x,0);
               // current_point.scrollTo(229+x*32,0);
            }
            if(position==1){
                int x= (int) positionOffset*32;
                current_point.scrollBy(-x,0);
               // current_point.scrollTo(-positionOffsetPixels,0);
            }*/
            /*Animation animation=null;
            if(offset<positionOffset){
                int x= (int) (positionOffset*32);
                current_point.scrollBy(x+32, 0);
               // animation=new TranslateAnimation(0,x,0,0);
               // current_point.startAnimation(animation);
                offset=positionOffset;
                System.out.println("11111111111111111111111111111   x = "+current_point.getScrollX());
            }
            if(offset>positionOffset){
                int x= (int) positionOffset*32;
                current_point.scrollTo(229 + x, 0);
                //animation=new TranslateAnimation(32,x,0,0);
                offset=positionOffset;
               // current_point.startAnimation(animation);
                System.out.println("222222222222222222222222222222   x = "+current_point.getScrollX());
            }*/
            // animation.setFillAfter(true);

        }

        @Override
        public void onPageSelected(int position) {

            Animation animation = null;
            //System.out.println("the onPageScrolled method parameters position value is : "+position+" positionOffset value is : "+positionOffset+"  positionOffsetPixels value is : "+positionOffsetPixels);
            if (currentIndex == 0) {
                animation = new TranslateAnimation(0, 31, 0, 0);
            }
            if (currentIndex == 1) {
                animation = new TranslateAnimation(31, 0, 0, 0);
            }
            currentIndex = position;
            animation.setFillAfter(true);
            animation.setDuration(300);
            current_point.startAnimation(animation);

            currentIndex = position;
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    private class GetDataTask extends AsyncTask<Void, Void, String[]> {

        @Override
        protected String[] doInBackground(Void... params) {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return new String[0];
        }

        @Override
        protected void onPostExecute(String[] strings) {
            super.onPostExecute(strings);
            refreshScrollView.onRefreshComplete();
        }
    }

    class MyAdapter extends BaseAdapter {

        Context mContext;
        LayoutInflater inflater;

        public MyAdapter(Context context) {
            mContext = context;
            inflater = LayoutInflater.from(mContext);
        }

        @Override
        public int getCount() {
            return 10;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            convertView = inflater.inflate(R.layout.tuan_listview_item, null);

            return convertView;
        }
    }

}
